<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tensorflow云计算</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" type="text/css" href="jquery/easyui1.4.2/themes/gray/easyui.css">
    <link rel="stylesheet" type="text/css" href="jquery/easyui1.4.2/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="css/assets/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="css/assets/css/ace.min.css"/>

    <script type="text/javascript" src="jquery/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="jquery/easyui1.4.2/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="jquery/easyui1.4.2/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="javascript/webuploader.js"></script>

    <script type="text/javascript" src="javascript/echarts/echarts-all-3.js"></script>
    <script type="text/javascript" src="javascript/echarts/ecStat.min.js"></script>
    <script type="text/javascript" src="javascript/echarts/dataTool.min.js"></script>

    <style type="text/css">
        .widget-box {
            border-bottom: 0px;
        }
        input[readonly] {
            background: #ffffff !important;
            cursor: default;
        }
    </style>
</head>
<body style="margin-top: 80px;background-color:white;">
<div class="widget-box" style="margin:16px 24px;padding-bottom:15px;text-align: center;">
    <div class="widget-header header-color-purple" style="border-top-left-radius:10px;border-top-right-radius:10px;">
        <h4 style="color:white;font-family: '微软雅黑'">tensorflow云计算</h4>
    </div>
    <div class="widget-body" style="border-bottom-right-radius:10px;border-bottom-left-radius:10px;">
        <div class="widget-main">
            <div>
                <p style="display: inline;font-family:'微软雅黑';font-weight: bold;font-size: large;color: red;vertical-align: middle;">提示：请下载说明文档
                    <a class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-filter'"
                       href="cloud_compute_document.docx">
                    </a>&nbsp;&nbsp;
                    <a href="pycflower.zip">想绘制曲线图？点这下载pycflower包！</a>
                </p><br><br>
            </div>
            <div id="my_list" style="font-size: large;vertical-align: middle;">
                用户检校码：
                <span id="checkID" style="font-family:'微软雅黑';font-weight: bold;font-size: large;">5ab069vbgo</span>
                &nbsp;&nbsp;云计算压缩包上传：
                <input id="zip_file_path" type="input" value="请上传压缩文件"
                       style="margin-left:5px;width: 280px;border: 2px solid #1a67bd ;"
                       onfocus="javascript:if(this.value=='请上传压缩文件')this.value='';">
                <button id="picker" style="display: none;"></button>
                <button id="pickerbtn" class="btn btn-sm btn-primary" style="margin-left: 15px ;margin-bottom:5px;border-width: 4px;font-size: 13px;" >
                    选择zip文件
                </button>
                <button id="uploadbtn" class="btn btn-sm btn-primary" style="margin-left: 15px ;margin-bottom:5px;border-width: 4px;font-size: 13px;">
                    上传并开始计算
                </button>
            </div>
            <div id="output_block" style="text-align:left;">
                <span style="margin-left: 52px;font-size: large;font-weight: bold;font-family:'微软雅黑' ">云计算输出窗口：</span>
                <div id="output_table"
                     style="padding: 0px 20px 0px 20px;text-align:left;overflow:auto;margin:10px 50px 10px 50px;height: 400px;border-radius: 10px 10px 10px 10px;border: 3px solid;border-color: black;">
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function(){
        $.ajax({													// 请求MD5
            cache: false,
            url: "analysis/md5",
            data: "",
            type: "POST",
            dataType: "text",
            success: function (result) {
                console.log(result);								// 将md5显示
                document.getElementById('checkID').innerText = result;
                websocketSet();
            }
        });
    })
    $('#pickerbtn').click(function () {
        $('#picker input[type="file"]').click();
    });

    var uploader = WebUploader.create({
        // swf文件路径
        swf: 'Uploader.swf',
        // 文件接收服务端。
        server: 'analysis/sparkupload',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker',
        resize: false,                            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        duplicate:true,                           //是否可重复选择同一文件
        fileNumLimit: 1,                          // 发送限制单文件
        fileSingleSizeLimit: 1000 * 1024 * 1024,    // 1000M
        fileVal:"file"                            //指明参数名称，后台也用这个参数接收文件
    });

    // 选择了文件后，在文件被添加进队列前
    uploader.on( 'beforeFileQueued', function( file ) {             // 发送限制单文件
        var fnum = uploader.getFiles().length;                        // 如果有文件在队列中
        if(fnum>0) uploader.reset();                                  // 清除队列
    });
    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
        var name=file.name;
        var fileName = name.substring(name.lastIndexOf(".")+1).toLowerCase();
        if(fileName !=='zip'){
            alert("请选择zip格式文件上传！");
            uploader.reset();
            return false;
        }
        // 获取检校码
        var check_id = document.getElementById('checkID').innerText;
        if(check_id.length==10)
        check_id=check_id.substring(1,9);
        // 判断压缩包文件名内是否包含检校码和邮箱
        if((name.indexOf(check_id) == -1) || (name.indexOf('@') == -1)) {
            alert("请参考说明文档，填写正确的压缩文件名！");
            uploader.reset();
            return false;
        }
        $('#zip_file_path').val(file.name);
        $('#my_list').append( '<div id="' + file.id + '" class="item">' +
            '<span class="info">文件： ' + file.name + '</span>' +
            '<span class="state">&nbsp;等待上传...</span>' +
            '</div>' );
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }
        $('#my_list').find('.state').text('   上传中');
        $percent.css( 'width', percentage * 100 + '%' );
    });

    uploader.on( 'error', function( type ) {             // 选择文件出错
        if(type=="F_EXCEED_SIZE"){
            alert("附件不能大于1G");
        }
    });
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
        $( '#'+file.id ).fadeOut();
        uploader.reset();
        $('#zip_file_path').val("请上传压缩文件");
    });
    $('#uploadbtn').on( 'click', function() {
        uploader.upload();
    });
    uploader.on( 'uploadAccept', function( file, response ) {
        if ( response.success==false ) {
            // 通过return false来告诉组件，此文件上传有错。
            alert('上传失败\r\n'+response.msg);
            $( '#'+file.id ).find('.progress').fadeOut();
            $( '#'+file.id ).fadeOut();
            return false;
        }
        else{
            alert('上传成功');
            $( '#'+file.id ).find('.progress').fadeOut();
            $( '#'+file.id ).fadeOut();
            $("#output_table").html();
        }
    });

    function websocketSet() {
        var errors;
        var wsPath = "ws://59.69.101.206:30480/cloud";
        // 获取检校码
        var check_id = document.getElementById('checkID').innerText;
        if(check_id.length==10)
            check_id=check_id.substring(1,9);
        var webSocket = new WebSocket(wsPath + '/websocket/'+ check_id);
        webSocket.onerror = function (event) {
            onError(event)
        };
        webSocket.onopen = function (event) {
            onOpen(event)
        };
        webSocket.onmessage = function (event) {
            onMessage(event)
        };
        // 数据点数组
        var pointArrCount;
        function onMessage(event) {
            console.log(event.data);

            // 将控制台输出加载到控制台窗口
            var o_table=document.getElementById("output_table");
            var strtxt = o_table.innerText;
            var consoleStr = JSON.parse(event.data).value;

            // 含有绘图标志
            if(consoleStr.indexOf("CFlower*")!=-1){
                var consoleArr = consoleStr.split('*');
                switch (consoleArr[1]){
                    case "loss":{
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_loss')[0];
                        // 没找到就加上并且初始化
                        if(container==undefined){
                            $('#output_block').prepend("<div id='e_container_loss' " +
                                "style='min-width: 200px; height: 300px;margin: 30px;'>" +
                                "</div>"
                            )
                            // 初始化后删除第一个没用的点
                            var myChart = init_loss_container()
                            var sel_option = myChart.getOption();
                            sel_option.series[0].data.splice(0,1);
                            myChart.setOption(sel_option);
                        }
                        // 获取echarts的dom对象
                        container = $('#e_container_loss')[0];
                        // 获取ec句柄
                        var myChart = echarts.getInstanceByDom(container)
                        // 增加点
                        var sel_option = myChart.getOption();
                        sel_option.series[0].data.push([new Date(), consoleArr[2]]);
                        sel_option.series[0].symbolSize=1;
//                    var data_point = sel_option.series[0].data;
//                    if(data_point.length > 1000) data_point.splice(0,1);
                        myChart.setOption(sel_option);
                        return;break;
                    }
                    case "data":{
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_data')[0];
                        // 没找到就加上并且初始化
                        if(container==undefined){
                            $('#output_block').prepend("<div id='e_container_data' " +
                                "style='min-width: 200px; height: 300px;margin: 30px;'>" +
                                "</div>"
                            )
                        }
                        // 初始化并删除所有系列
                        var myChart = init_data_container();
                        var sel_option = myChart.getOption();
                        sel_option.series = null;
                        myChart.clear();
                        myChart.setOption(sel_option)

                        // 增加系列
                        var sel_option = myChart.getOption();
                        for(var i=0;i<(consoleArr.length-2);i++){
                            var temstrArr = consoleArr[i+2];
                            temstrArr = temstrArr.split('?');
                            var series_name = temstrArr[0];
                            var data_arr = temstrArr[1].split(',');

                            sel_option.series.push({									// 将获取到的系列加到表格中
                                name: series_name,
                                type:'line',
                                symbolSize:1,
                                data: (function () {
                                    var d = [];
                                    var sample_rate;
                                    var sample_num=1500;

                                    // 数据量大时抽样
                                    if (data_arr.length > 1600)
                                        sample_rate = parseInt(data_arr.length / sample_num);
                                    else // 小于1600组不抽样
                                        sample_rate = 0;

                                    if(sample_rate == 0)        // 加载不抽样数据
                                    {
                                        for (var j = 0; j < data_arr.length; j++) {
                                            d.push([j, parseFloat(data_arr[j]).toFixed(6)]);
                                        }
                                    }
                                    else                        // 加载抽样数据
                                    {
                                        for (var j = 0; j < sample_num; j++) {
                                            d.push([j, parseFloat(data_arr[j*sample_rate]).toFixed(6)]);
                                        }
                                    }
                                    return d;
                                })()
                            });
                        }
                        myChart.setOption(sel_option);
                        return;break;
                    }
                    case "title": {
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_data')[0];
                        if(container!=undefined){
                            // 获取echarts的dom对象
                            container = $('#e_container_data')[0];
                            // 获取ec句柄
                            var myChart = echarts.getInstanceByDom(container)
                            myChart.setOption({title: {text: consoleArr[2]}});
                        }
                        return;break;
                    }
                    case "xAxisName": {
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_data')[0];
                        if(container!=undefined){
                            // 获取echarts的dom对象
                            container = $('#e_container_data')[0];
                            // 获取ec句柄
                            var myChart = echarts.getInstanceByDom(container)
                            myChart.setOption({xAxis: {name: consoleArr[2]}});
                        }
                        return;break;
                    }
                    case "yAxisName": {
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_data')[0];
                        if(container!=undefined){
                            // 获取echarts的dom对象
                            container = $('#e_container_data')[0];
                            // 获取ec句柄
                            var myChart = echarts.getInstanceByDom(container)
                            myChart.setOption({yAxis: {name: consoleArr[2]}});
                        }
                        return;break;
                    }
                    case "series":{
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_data')[0];
                        // 没找到就加上
                        if(container==undefined){
                            $('#output_block').prepend("<div id='e_container_data' " +
                                "style='min-width: 200px; height: 300px;margin: 30px;'>" +
                                "</div>"
                            )
                        }
                        // 初始化并删除所有系列
                        var myChart = init_data_container();
                        var sel_option = myChart.getOption();
                        sel_option.series = null;
                        myChart.clear();
                        myChart.setOption(sel_option)

                        // 初始化系列
                        var sel_option = myChart.getOption();
                        var series_names = consoleArr[2].split(',');
                        // 点计数数组重新设定大小
                        pointArrCount = new Array();
                        series_names.forEach(function(item) {
                            sel_option.series.push({									// 将获取到的系列加到表格中
                                name: item,
                                type:'line',
                                symbolSize:1,
                                data:(function () {
                                    var d = [];
                                    d.push([0, 0]);
                                    return d;
                                })()
                            });
                            pointArrCount.push(0);
                        });
                        sel_option.series.forEach(function(item) {
                            item.data.splice(0,1);
                        });
                        myChart.setOption(sel_option);

                        return;break;
                    }
                    case "point": {
                        // 查找echarts的dom对象
                        var container = $('#output_block').find('#e_container_data')[0];
                        if(container!=undefined){
                            // 获取echarts的dom对象
                            container = $('#e_container_data')[0];
                            // 获取ec句柄
                            var myChart = echarts.getInstanceByDom(container)
                            var sel_option = myChart.getOption();
                            var series_point = consoleArr[2].split(',');
                            for(var j=0;j<sel_option.series.length;j++){
                                if(sel_option.series[j].name==series_point[0]){
                                    pointArrCount[j]++;
                                    sel_option.series[j].data.push([pointArrCount[j], parseFloat(series_point[1]).toFixed(6)]);
                                    sel_option.series[j].symbolSize=1;
                                    break;
                                }
                            }
                            myChart.setOption(sel_option);
                        }
                        return;break;
                    }
                    default:break;
                }
            }

            // 没有绘图标志就正常显示控制台
            strtxt = strtxt + '\n' + consoleStr;
            o_table.innerText = strtxt;
            o_table.scrollTop=o_table.scrollHeight;
        }
        function onOpen(event) {
            console.log("Cloud compute started！")
        }
        function onError(event) {
            console.log(event.data)
        }
        return true;
    }

    function init_loss_container() {
        var myChart = echarts.init(document.getElementById('e_container_loss'));
        myChart.setOption(option = {
            title: {
                text: '损失函数图',
                x: 'left'
            },
            xAxis : [{
                type : 'time',
                splitNumber:10,
                boundaryGap: false,
            }],
            yAxis: {
                type: 'value',
                name: 'loss',
                scale: true,
                splitLine: {
                    show: false
                }
            },
            toolbox: {
                left: 'center',
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    restore: {},
                    saveAsImage: {}
                }
            },
            dataZoom: [{
                type: 'slider',
                show : true,
                realtime: true,
                start: 30,
                end:70
            }, {
                type: 'inside',
                start: 30,
                end: 70

            }],
            tooltip: {
                trigger: 'axis'
            },
            series: [{
                name:'loss',
                type:'line',
                data: (function () {
                    var d = [];
                    var time = (new Date()).getTime(), i;
                    for (i = -1; i < 0; i += 1) {
                        d.push([
                            time + i * 1000, 0
                        ]);
                    }
                    return d;
                })()
            }]
        });
        return myChart;
    }
    function init_data_container() {
        var myChart = echarts.init(document.getElementById('e_container_data'));
        myChart.setOption(option = {
            animation:false,
            title: {
                text: '数据对比图',
                x: 'left'
            },
            xAxis : [{
                type : 'value',
                splitNumber:10,
                boundaryGap: false,
            }],
            yAxis: {
                type: 'value',
                name: '值',
                scale: true,
                splitLine: {
                    show: false
                }
            },
            toolbox: {
                left: 'center',
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    restore: {},
                    saveAsImage: {}
                }
            },
            dataZoom: [{
                type: 'slider',
                show : true,
                realtime: true,
                start: 0,
                end:100
            }, {
                type: 'inside',
                start: 0,
                end: 100

            }],
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    var retStr = new String();
                    params.forEach(function(item) {
                        retStr += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + item.color + '"></span>';
                        retStr += item.seriesName + ' : ' + item.value[1] + '<br>';
                    });
                    return retStr;
                }
            }
        });
        return myChart;
    }
</script>
</body>
</html>
